package org.yinxue.example.spiderx.domain.utils.spider;



import org.yinxue.example.spiderx.domain.utils.model.ATag;
import org.yinxue.example.spiderx.domain.utils.model.ImgTag;
import org.yinxue.example.spiderx.domain.utils.util.SetArrayList;
import org.yinxue.example.spiderx.domain.utils.util.SetLinkedList;

import java.util.Collections;
import java.util.List;

/**
 * CircleSpider {@link org.yinxue.spider.core.spider}
 *
 * @author zengjian
 * @date 2019/2/13
 * @since 1.0.0
 */
public class CircleSpider extends Spider {

    private volatile boolean running = true;
    private SetLinkedList<ATag> runningAtags = new SetLinkedList<>();

    private SetArrayList<ATag> aTags = new SetArrayList<>();
    private SetArrayList<ImgTag> imgTags = new SetArrayList<>();

    public void start(String url) {
        runningAtags.add(new ATag(url));
        while (running) {
            // 从队列中获取第一个A标签
            ATag runAtag = runningAtags.removeFirst();
            String runUrl = runAtag.getUrl();
            List<ATag> preAtags = parseATag(runUrl);
            aTags.add(runAtag);
            imgTags.addAll(parseImgTag(runUrl));
            runningAtags.addAll(preAtags);
        }
    }

    public void stop() {
        this.running = false;
    }

    public List<ATag> getAtags() {
        // 按字母排序后输出
        Collections.sort(aTags);
        return aTags;
    }

    public List<ImgTag> getImgTags() {
        // 按字母排序后输出
        Collections.sort(imgTags);
        return imgTags;
    }
}